package com.isoft.c2team3service2.config;

import com.isoft.c2team3service2.util.UserHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.concurrent.TimeUnit;

import static com.isoft.c2team3service2.util.RedisConstants.USER_LOGIN_KEY;

/**
 * @author 蓝莓
 * @date 2025/10/21 11:43
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {
//    //这个对象是我们自己new出来的，并没有交给spring，无@Commonpent注解，所以我们自己来构造器注入
    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getHeader("Authorization") == null) {
            return true;
        }
        String token = request.getHeader("Authorization").substring(7);
        stringRedisTemplate.expire(USER_LOGIN_KEY + token, 30, TimeUnit.MINUTES);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
